/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.hiddendanger.bean.SafetyObservBean;
import com.koron.hiddendanger.domain.ObservRecord;
import com.koron.hiddendanger.mapper.ObservRecordMapper;
import com.koron.hiddendanger.mapper.SafetyObservMapper;
import com.koron.hiddendanger.service.api.SafetyObservService;
import com.koron.risk.service.impl.GridNodeServiceImpl;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SafetyObservServiceImpl implements SafetyObservService {
    private final static Logger logger = LoggerFactory.getLogger(SafetyObservServiceImpl.class);

    @Autowired
    private GridNodeServiceImpl gridNodeService;
    @Autowired
    private Util util;

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> insert(SafetyObservBean bean, StaffBean user) {
        MessageBean<SafetyObservBean> msg = MessageBean.create(0, "success", SafetyObservBean.class);
        Map checkMap = addCheck(bean);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
        Calendar calendar = Calendar.getInstance();
        Calendar nowCalendar = Calendar.getInstance();
        calendar.setTime(bean.getObservDate());
        nowCalendar.setTime(new Date());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int nowYear = nowCalendar.get(Calendar.YEAR);
        int nowMonth = nowCalendar.get(Calendar.MONTH);
        if (year != nowYear) {
            msg.setCode(22002);
            msg.setDescription("只能新增当月数据");
            return msg;
        }
        if (month != nowMonth) {
            msg.setCode(22002);
            msg.setDescription("只能新增当月数据");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            bean.setAddTime(new Date());
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            Map<String, String> positionMap = gridNodeService.getPositionMap();
            if (!StringUtils.isEmpty(bean.getGridCode())) {
                bean.setGridLabel(positionMap.get(bean.getGridCode())); //观察位置
            } else {
                bean.setGridCode("");
            }
            List<ObservRecord> behaviorList = bean.getBehaviorList();
            int safetyNumber = 0;
            int unsafeNumber = 0;
            for (ObservRecord observRecord : behaviorList) {
                observRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                observRecord.setSafetyObservId(bean.getId());
                if (1 == observRecord.getIshappen()) {
                    if (observRecord.getIssafety() == 0) { //不安全行为
                        unsafeNumber++;
                    }
                    if (observRecord.getIssafety() == 1) {
                        safetyNumber++;
                    }
                }
            }
            bean.setSafetyNumber(safetyNumber);
            bean.setUnsafeNumber(unsafeNumber);
            factory.getMapper(ObservRecordMapper.class).batchInsert(behaviorList);
            factory.getMapper(SafetyObservMapper.class).insert(bean);
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(22001);
            msg.setDescription("数据库连接异常");
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> update(SafetyObservBean bean, StaffBean user) {
        MessageBean<SafetyObservBean> msg = MessageBean.create(0, "success", SafetyObservBean.class);
        if (StringUtils.isEmpty(bean.getId())) {
            msg.setCode(22002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SafetyObservBean oldBean = queryById(bean.getId());
        if (oldBean == null) {
            msg.setCode(22002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        if (!oldBean.getAddUser().equals(user.getCode())) {
            msg.setCode(22002);
            msg.setDescription("无权限修改");
            return msg;
        }
        Map checkMap = addCheck(bean);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
        Calendar calendar = Calendar.getInstance();
        Calendar oldCalendar = Calendar.getInstance();
        calendar.setTime(bean.getObservDate());
        oldCalendar.setTime(oldBean.getObservDate());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int oldYear = oldCalendar.get(Calendar.YEAR);
        int oldMonth = oldCalendar.get(Calendar.MONTH);
        if (year != oldYear) {
            msg.setCode(22002);
            msg.setDescription("只能修改当月数据");
            return msg;
        }
        if (month != oldMonth) {
            msg.setCode(22002);
            msg.setDescription("只能修改当月数据");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            Map<String, String> positionMap = gridNodeService.getPositionMap();
            bean.setGridLabel(positionMap.get(bean.getGridCode())); //观察位置
            List<ObservRecord> behaviorList = bean.getBehaviorList();

            int safetyNumber = 0;
            int unsafeNumber = 0;
            for (ObservRecord observRecord : behaviorList) {
                observRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                observRecord.setSafetyObservId(bean.getId());
                if (1 == observRecord.getIshappen()) {
                    if (observRecord.getIssafety() == 0) { //不安全行为
                        unsafeNumber++;
                    }
                    if (observRecord.getIssafety() == 1) {
                        safetyNumber++;
                    }
                }
            }
            bean.setSafetyNumber(safetyNumber);
            bean.setUnsafeNumber(unsafeNumber);
            //删除原来的行为数据
            factory.getMapper(ObservRecordMapper.class).delete(bean.getId());
            factory.getMapper(ObservRecordMapper.class).batchInsert(behaviorList);
            factory.getMapper(SafetyObservMapper.class).update(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(22001);
            msg.setDescription("数据库连接异常");
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> delete(String id, StaffBean user) {
        MessageBean<SafetyObservBean> msg = MessageBean.create(0, "success", SafetyObservBean.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(22002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SafetyObservBean bean = queryById(id);
        if (bean == null) {
            msg.setCode(22002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        if (!bean.getAddUser().equals(user.getCode())) {
            msg.setCode(22002);
            msg.setDescription("无权限删除");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            factory.getMapper(SafetyObservMapper.class).delete(id);
            factory.getMapper(ObservRecordMapper.class).delete(id);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(22001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes", "unchecked"})
    @Override
    public MessageBean<?> list(String observerCode, String observerName, String corpCode, String behaviorTypeId,
                               String gridCode, String deptCode, Date biginDate, Date endDate, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        if (StringUtils.isEmpty(corpCode)) {
            return msg;
        }
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        try (SessionFactory factory = new SessionFactory()) {
            totalNumber = factory.getMapper(SafetyObservMapper.class).count(observerCode, observerName, corpCode, behaviorTypeId, gridCode, deptCode, biginDate, endDate);
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            List<SafetyObservBean> list = factory.getMapper(SafetyObservMapper.class).list(observerCode, observerName, corpCode, behaviorTypeId, gridCode, deptCode, biginDate, endDate, start, end);
            DataBean data = new DataBean();
            data.setList(list);
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes", "unchecked"})
    @Override
    public MessageBean<?> details(String id) {
        MessageBean<SafetyObservBean> msg = MessageBean.create(0, "success", SafetyObservBean.class);
        SafetyObservBean bean = queryById(id);
        if (bean == null) {
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            List<ObservRecord> behaviorList = factory.getMapper(ObservRecordMapper.class).queryByTid(id);
            List<DictData> ddList = factory.getMapper(DictDataMapper.class).queryByDictName(bean.getBehaviorTypeName());
            if (ddList.isEmpty()) {
                bean.setBehaviorList(behaviorList);
            } else { //分页签返回数据
                List<Map> detailsList = new ArrayList<Map>();
                for (DictData dictData : ddList) {
                    Map map = new HashMap();
                    map.put("name", dictData.getDictLabel());
                    List<ObservRecord> temp = behaviorList.stream().filter(s -> s.getBehaviorType().equals(dictData.getId())).collect(Collectors.toList());
                    map.put("list", temp);
                    detailsList.add(map);
                }
                bean.setDetailsList(detailsList);
            }

        } catch (Exception e) {
            return msg;
        }
        msg.setData(bean);
        return msg;
    }

    @Override
    public List<SafetyObservBean> exportList(StaffBean user, String corpCode, String observerCode, String observerName, String gridCode, String behaviorTypeId, String deptCode, Date biginDate, Date endDate) {
        try (SessionFactory factory = new SessionFactory()) {
            List<SafetyObservBean> list = factory.getMapper(SafetyObservMapper.class).list(observerCode, observerName, corpCode, behaviorTypeId, gridCode, deptCode, biginDate, endDate, null, null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                list.forEach(bean -> {
				    if (null != bean.getObservDate()){
				        bean.setObservDateStr(sdf.format(bean.getObservDate()));
                    }
                    if (!StringUtils.isEmpty(bean.getObserverName())){
                        bean.setObserverName(bean.getObserverName().split("_")[0]);
                    }
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @SuppressWarnings("deprecation")
    public SafetyObservBean queryById(String id) {
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(SafetyObservMapper.class).queryById(id);
        } catch (Exception e) {
            return null;
        }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map addCheck(SafetyObservBean bean) {
        Map map = new HashMap();
        if (bean == null) {
            map.put("code", 22002);
            map.put("description", "请填写观察信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getObserverCode())) {
            map.put("code", 22002);
            map.put("description", "请填写观察人信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getCorpCode())) {
            map.put("code", 22002);
            map.put("description", "请填写观察公司信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getGridName())) {
            map.put("code", 22002);
            map.put("description", "请填写观察区域信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getNote())) {
            map.put("code", 22002);
            map.put("description", "请填写观察内容");
            return map;
        }
        if (StringUtils.isEmpty(bean.getObservDate())) {
            map.put("code", 22002);
            map.put("description", "请填写观察日期");
            return map;
        }
        if (null == bean.getObservHours()) {
            map.put("code", 22002);
            map.put("description", "请填写观察时长");
            return map;
        }
        List<ObservRecord> orList = bean.getBehaviorList();
        if (orList.isEmpty()) {
            map.put("code", 22002);
            map.put("description", "行为列表不能为空");
            return map;
        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;
    }
}
